package cn.tedu.sp06.filter;


import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import io.micrometer.core.instrument.util.StringUtils;
import jdk.nashorn.internal.scripts.JO;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //设置成前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        /**
         * 调用商品需要权限
         * 调用用户或者订单不检查权限
         */
        //1.需要获得一个请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //2.从上下文对象获得调用的后台服务的service
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);//"serviceId"
        //如果调用的是item-service额,返回TRUE

        return "item-service".equals(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //获得request 对象
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        // 如果token不存在
        if (StringUtils.isBlank(token)) {
            //作用:阻止继续调用
            ctx.setSendZuulResponse(false);//发送zuul响应
            String json = JsonResult.build().code(400).msg("No Login! 未登录!").toString();
            ctx.addZuulResponseHeader(
                    "Content-Type", "application/json;charset=UTF-8");

            ctx.setResponseBody(json);

        }


        return null;//Zuul当前这个版本返回值不起任何作用
    }
}
